#include "mainview.h"
#include "ui_mainview.h"
#include <QPainter>
#include <QPrinter>
#include <QPrintDialog>
#include <QPaintEvent>
#include <QMessageBox>

MainView::MainView(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::MainView), gpxFileModel(0), resultsModel(0)
{
    ui->setupUi(this);
    //this->setFixedSize(this->width(),this->height());

    // Set up the file list
    setupWidgets();
}

MainView::~MainView()
{
    delete ui;
}

void MainView::setupWidgets()
{
    gpxFileModel = new QStandardItemModel(0,2);
    QStringList headerLabels;
    headerLabels << tr("Name") << tr("Filename");
    gpxFileModel->setHorizontalHeaderLabels(headerLabels);
    // Set up our file table
    ui->fileList->setColumnWidth(0, 100);
    ui->fileList->setColumnWidth(1, 1000);
    ui->fileList->setModel(gpxFileModel);
    ui->fileList->setShowGrid(true);


    // And the intersection table
    resultsModel = new QStandardItemModel(0, 2);

    resetOutputGrid();
}

void MainView::addFile()
{
    QFileDialog fd;
    QStringList filters;
    filters << "GPX files (*.gpx)";
    fd.setNameFilters(filters);
    fd.setFileMode(QFileDialog::ExistingFiles);
    QStringList fileNames;
    if ( fd.exec() == QDialog::Accepted )
    {
        fileNames = fd.selectedFiles();

        // Now add it to the list
        addFilesToProcess(fileNames);
    }
}

void MainView::addFilesToProcess(const QStringList& fileNames)
{
    int fileNamesSize = fileNames.size();
    for (int fileNum = 0; fileNum < fileNamesSize; ++fileNum)
    {
        QStandardItem* item = new QStandardItem(QString("%0").arg(fileNames.at(fileNum)));

        gpxFileModel->setItem(gpxFileModel->rowCount(), 1, item);
    }
}

void MainView::removeFile()
{
    if (selectedFileModelIndex.isValid())
    {
        gpxFileModel->removeRow(selectedFileModelIndex.row());
    }
}

bool MainView::processFiles()
{
    qDebug() << "Processing " << gpxFileModel->rowCount() << " files";

    //
    // Okay, now for each file, load 'em up and process them
    //
    int fileCount = gpxFileModel->rowCount();
    for (int fileNum = 0; fileNum < fileCount; ++fileNum)
    {
        QStandardItem* personNameData = gpxFileModel->item(fileNum, 0);
        if (personNameData == 0)
        {
            QMessageBox::critical( this, "TGP",
                    QString("Please set the name of the GPX file"));

            // Didn't add a name
            ui->fileList->selectRow(fileNum);
            return false;
        }
        else
        {
            QString personName =  gpxFileModel->item(fileNum, 0)->index().data().value<QString>();
            QString theFilename =  gpxFileModel->item(fileNum, 1)->index().data().value<QString>();
            qDebug() << "Processing " << personName << " - " << theFilename;

            // Now do the parsing
            GPXParser parser;
            parser.parseFile(theFilename.toAscii());

            // Now we're going to add it to the map
            dataSet.insert(std::make_pair(personName.toAscii(), parser.getCaches()));
        }
    }

    return true;
}

void MainView::resetOutputGrid()
{
    resultsModel->clear();

    QStringList interLabels;
    interLabels << tr("Cache ID") << tr("Description");
    resultsModel->setHorizontalHeaderLabels(interLabels);
    // Set up our intersection table
    ui->intersectionTable->setColumnWidth(0, 100);
    ui->intersectionTable->setColumnWidth(1, 1000);
    ui->intersectionTable->setModel(resultsModel);
    ui->intersectionTable->setShowGrid(true);
}

void MainView::showCommon()
{
    resetOutputGrid();

    if (processFiles() == false)
        return;

    // Now we're done loading the GPX files and have them assigned to the
    // appropriate person, so let's get on with the show!
    SolverIntersection solver(dataSet);

    // Here we're doing the actual work in figuring out which caches are
    // common to all
    solver.findCommonCaches();

    // And we're all done, so let's print the results
    if (solver.getCommonCaches().size() == 0)
    {
        qDebug() << "No caches common to everyone";
    }
    else
    {
        qDebug() << "Here is the list of caches that everyone needs to do:";
        for (std::vector<cache>::iterator comIt = solver.getCommonCaches().begin(); comIt
                != solver.getCommonCaches().end(); ++comIt)
        {
            qDebug() << comIt->cacheName.c_str() << " - " << comIt->cacheDesc.c_str();

            int currentRow = resultsModel->rowCount();

            // Cache ID
            QStandardItem* cacheIDItem = new QStandardItem(QString("%0").arg(comIt->cacheName.c_str()));
            resultsModel->setItem(currentRow, 0, cacheIDItem);

            // Cache description
            QStandardItem* cacheDescItem = new QStandardItem(QString("%0").arg(comIt->cacheDesc.c_str()));
            resultsModel->setItem(currentRow, 1, cacheDescItem);
        }
    }

    ui->intersectionTable->resizeColumnsToContents();
    ui->intersectionTable->resizeRowsToContents();
}

void MainView::showDifference()
{
    resetOutputGrid();

    if (processFiles() == false)
        return;

    // Now we're done loading the GPX files and have them assigned to the
    // appropriate person, so let's get on with the show!
    SolverDifference solver(dataSet);

    // Here we're doing the actual work in figuring out which caches are
    // common to all
    solver.findDifferentCaches();

    // And we're all done, so let's print the results
    if (solver.getDifferentCaches().size() == 0)
    {
        qDebug() << "No caches different to everyone";
    }
    else
    {
        qDebug() << "Here is the list of caches that are different";
        for (std::vector<cache>::iterator comIt = solver.getDifferentCaches().begin(); comIt
                != solver.getDifferentCaches().end(); ++comIt)
        {
            qDebug() << comIt->cacheName.c_str() << " - " << comIt->cacheDesc.c_str();

            int currentRow = resultsModel->rowCount();

            // Cache ID
            QStandardItem* cacheIDItem = new QStandardItem(QString("%0").arg(comIt->cacheName.c_str()));
            resultsModel->setItem(currentRow, 0, cacheIDItem);

            // Cache description
            QStandardItem* cacheDescItem = new QStandardItem(QString("%0").arg(comIt->cacheDesc.c_str()));
            resultsModel->setItem(currentRow, 1, cacheDescItem);
        }
    }

    ui->intersectionTable->resizeColumnsToContents();
    ui->intersectionTable->resizeRowsToContents();
}

void MainView::saveResults()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save file"), QString(), tr("Text (*.csv *.txt)"));
    if (fileName.length())
    {
        QFile file(fileName);
        file.open(QIODevice::WriteOnly);

        int rowCount = resultsModel->rowCount();
        QTextStream out(&file);
        for (int row = 0; row < rowCount; ++row)
        {
            QString cacheName =  resultsModel->item(row, 0)->index().data().value<QString>();
            QString cacheDesc =  resultsModel->item(row, 1)->index().data().value<QString>();
            out << """" << cacheName << """,""" << cacheDesc << """\n";
        }

        file.close();
    }
}
